<?
class CheckoutController extends BaseController {
    var $step;
    var $total_step = 2;
    var $cart;
    var $bill_generated = array();
    public function __construct(){
        parent::__construct();
        $this->checkUserLogin();
        $this->step = getValue('step','int','POST',1,3);
        $this->cart = json_decode(base64_decode(getValue('cart','str','COOKIE','',3)),1);
        //Nếu đang ở bước 2 thì tạo hóa đơn
        if($this->step == 2){
            $this->bill_generated = $this->generateBill();
        }
    }

    public function getBreadCrumb(){
        $array = array('url'=>generate_checkout_url());
        return CheckoutLayout::generate_breadcrumb($array);
    }

    /*
     * Kiểm tra đăng nhập - nếu chưa đăng nhập thì cho chuyển đến trang đăng nhập
     */
    public function checkUserLogin(){
        $myuser = new user();
        $url_return = $_SERVER['REQUEST_URI'];
        $link_redirect = link_redirect(generate_login_url(), $url_return);
        if(!$myuser->logged()){
            redirect($link_redirect);
        }else{
            return true;
        }

    }

    /*
     * Hàm lấy ra phần header bước thanh toán
     */
    public function getStepCheckout(){
        if($this->step) {
            switch($this->step){
                case 1:
                    $array = array('step'=>1,'title'=>'Kiểm tra thông tin đơn hàng','total'=>$this->total_step);
                    break;
                case 2:
                    $array = array('step'=>2,'title'=>'Thanh toán đơn hàng','total'=>$this->total_step);
                    break;
            }

            $html = CheckoutLayout::step_checkout($array);
            return $html;
        }
    }
    public function getReviewInfoUser(){
        $myuser = new user();
        if($myuser->logged()){
            $array = array(
                'name'=>$myuser->fullname,
                'email'=>$myuser->email,
                'phone'=>$myuser->phone,
                'address'=>$myuser->contact
            );
            return CheckoutLayout::review_info_user($array);
        }
    }
    public function getReviewInfoCart(){
        if(!$this->cart){
            return ;
        }
        $total = 0;
        $list = array();
        foreach($this->cart as $k=>$v){
            $db_query = new db_query('SELECT pro_id,
                                             pro_thumb,
                                             pro_name,
                                             pro_price
                                      FROM   products
                                      WHERE  pro_id = '.$k);
            $row = mysql_fetch_assoc($db_query->result);unset($db_query);
            $subtotal = (int) ($row['pro_price'] * $v);
            $total += $subtotal;
            $tmp = array(
                'thumb'=>PATH_PICTURE_PRODUCT_SMALL . $row['pro_thumb'],
                'name'=>$row['pro_name'],
                'link'=>generate_product_detail_url($row),
                'price'=>format_price($row['pro_price']),
                'sub_total'=>format_price($subtotal),
                'num'=> $v
            );
            $list[] = $tmp;
        }
        return CheckoutLayout::review_info_cart(array('total'=>format_price($total), 'list'=>$list));
    }

    /*
     * Tạo hóa đơn hàng dựa vào user và cart
     */
    public function generateBill(){
        $myuser = new user();
        $time = time();
        //check xem hóa đơn hiện tại là hóa đơn thứ mấy trong ngày
        $begin_time = getBeginTimeToday();
        $end_time = getEndTimeToday();
        $db_query = new db_count('SELECT count(*) as count
                                  FROM bills
                                  WHERE bil_date > '.$begin_time.'
                                  AND bil_date < '.$end_time);
        $count = $db_query->total;unset($db_query);
        //Tạo mã hóa đơn
        $bil_code = 'HD'.date('Y',$time) . '-' . date('m',$time) . '-' . date('d',$time).'-'.($count+1);
        //Lấy thông tin đơn hàng
        $str_product_id = '';
        $bil_product_number_info = array();
        $total_money = 0;
        foreach($this->cart as $k=>$v){
            $str_product_id = $k.',';
        }
        $str_product_id = rtrim($str_product_id,',');
        if(!$str_product_id){
            return false;
        }
        $db_query = new db_query('SELECT pro_id,pro_price,pro_name,pro_thumb,fac_name
                                  FROM products
                                  LEFT JOIN factory ON fac_id = pro_factory
                                  WHERE pro_id IN('.$str_product_id.')');
        while($row = mysql_fetch_assoc($db_query->result)){
            $total_money += (int)$row['pro_price'] * (int)$this->cart[$row['pro_id']];
            $bil_product_number_info[$row['pro_id']] = array('price'=>$row['pro_price'],
                                                        'thumb'=>$row['pro_thumb'],
                                                        'number'=>$this->cart[$row['pro_id']],
                                                        'name'=>$row['pro_name'],
                                                        'fac_name'=>$row['fac_name']);
        }
        $bil_product_number_info = base64_encode(json_encode($bil_product_number_info));
        //Tổng tiền của hóa đơn
        $bil_money_before_transport_fee = $bil_money_after_transport_fee = $total_money;
        $bil_transport_address = $myuser->contact;
        $bil_status = 0;
        $sql = 'INSERT INTO bills (bil_code,bil_product_number_info,
                                    bil_date,bil_user_id,bil_status,
                                    bil_money_before_transport_fee,
                                    bil_money_after_transport_fee,
                                    bil_transport_address)
                    VALUES("'.$bil_code.'",
                            "'.$bil_product_number_info.'",
                            "'.$time.'",
                            "'.$myuser->u_id.'",
                            "'.$bil_status.'",
                            "'.$bil_money_before_transport_fee.'",
                            "'.$bil_money_after_transport_fee.'",
                            "'.$bil_transport_address.'")';
        $db_insert = new db_execute_return();
        $last_id = $db_insert->db_execute($sql);
        if($last_id){
            return array(
                'id'=>$last_id,
                'code'=>$bil_code,
                'info'=>$bil_product_number_info,
                'date'=>$time,
                'uid'=>$myuser->u_id,
                'status'=>$bil_status,
                'money_before'=>$bil_money_before_transport_fee,
                'money_after'=>$bil_money_after_transport_fee,
                'address'=>$bil_transport_address
            );
        }else{
            return false;
        }
    }

    public function getNextStepButton(){
        switch($this->step){
            case 1:
                $title = 'Thanh toán đơn hàng';
                break;
        }
        if($this->step == 2){
            return '';
        }
        return CheckoutLayout::next_step_checkout(array('title'=>$title,'step'=>$this->step));
    }
}
?>